package com.example.common.dialog;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import com.example.commonlib.R;


/**
 * Desc： 进度弹窗,可设置进度值
 *
 * @author xmqian
 * Email:xmqian93@163.com
 * Date: 2020/8/14 0014 15:36
 */
public class ProgressDialog extends AlertDialog {
    /**
     * 弹窗默认标题
     */
    private final String TITLE = "加载中，请稍等";
    private ProgressBar progressBar;
    private TextView tvProgress;
    private int maxProgress = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /*Window window = getWindow();
        if (window != null) {
            NavigationBarUtils.hideNavigationBar(window, getContext());
        }*/
    }

    public ProgressDialog(@NonNull Context context) {
        super(context);
        progressBar = (ProgressBar) LayoutInflater.from(context).inflate(R.layout.com_dialog_progress_bar, null);
        progressBar.setMax(maxProgress);
        tvProgress = new TextView(context);
        LinearLayout linearLayout = new LinearLayout(context);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.addView(progressBar);
        linearLayout.addView(tvProgress);
        setView(linearLayout, 50, 50, 50, 50);
        setCanceledOnTouchOutside(false);
        setTitle(TITLE);
    }


    public void setMaxProgress(int max) {
        if (max > 0) {
            this.maxProgress = max;
            if (progressBar != null) {
                progressBar.setMax(max);
            }
        }
    }

    public int getMaxProgress() {
        return maxProgress;
    }

    public void refreshProgress(int progress) {
        if (progressBar != null && isShowing()) {
            progressBar.setProgress(progress);
        }
        if (tvProgress != null && isShowing()) {
            tvProgress.setText(String.format("进度: %d / %d", progress, maxProgress));
        }
        if (progress >= maxProgress) {
            if (isShowing()) {
                dismiss();
            }
        }
    }

    /**
     * 清除进度数据
     * 需要在设置其他数据之前执行
     */
    public void reset() {
        setMaxProgress(100);
        refreshProgress(0);
        setTitle(TITLE);
        if (tvProgress != null) {
            tvProgress.setText("");
        }
    }

    @Override
    public void show() {
        super.show();
    }
}
